package com.hrbxlh.actionImpl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import jxl.Sheet;
import jxl.Workbook;

//import org.apache.poi.hssf.record.formula.functions.Isblank;
//import org.apache.poi.hssf.usermodel.HSSFCell;
//import org.apache.poi.hssf.usermodel.HSSFRow;
//import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.dao.CourseDao;
import com.hrbxlh.dao.MyCourseDao;
import com.hrbxlh.dao.QuestionDao;
import com.hrbxlh.dao.RelStuClassDao;
import com.hrbxlh.dao.RelationDao;
import com.hrbxlh.dao.SourceDao;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.pageUtil;

@Component("questionActionImpl")
@Transactional
public class QuestionActionImpl {
	
	@Resource(name="questionDao")
	private QuestionDao questionDao;
	
	@Resource(name="courseDao")
	private CourseDao courseDao;
	
	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;
	
	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;
	
	@Resource(name = "relationDao")
	private RelationDao relationDao;
	
	@Resource(name="sourceDao")
	private SourceDao sourceDao;
	
	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;
	
	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllQuestionList(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId = "8888888";
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//通过教师号获取此教师所属课程
			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
			returnMap.put("courseList", courseList);
			/*
			
			if(courseList!=null&&courseList.size()!=0){
				returnMap.put("courseList", courseList);
				paramMap.put("courseList", courseList);
				System.out.println("最后的map"+paramMap);
				//查询题库列表
				List<Map<String, Object>> questionList = questionDao.getAllQuestionList(paramMap);
				returnMap.put("questionList", questionList);
				returnMap.put("pageNow", pageNow);
				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = questionDao.getAllQuestionList(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
				returnMap.put("flag", "success");
			}else{
				//说明此教师没有课程
				returnMap.put("flag", "fail");
				returnMap.put("errMsg", "因此教师没有课程所以题库为空");
			}
			*/
			//查询所有课程
			List<Map<String,Object>> courseListAll = courseDao.getAllCourse();
			returnMap.put("courseListAll", courseListAll);
			//查询题库列表
			List<Map<String, Object>> questionList = questionDao.getAllQuestionList(paramMap);
			returnMap.put("questionList", questionList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = questionDao.getAllQuestionList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			returnMap.put("flag", "success");
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllQuestionListExcel(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int optionPageNow = Integer.valueOf(String.valueOf(paramMap.get("optionPageNow")));
			int optionPageSize = Integer.valueOf(String.valueOf(paramMap.get("optionPageSize")));
			int judgePageNow = Integer.valueOf(String.valueOf(paramMap.get("judgePageNow")));
			int judgePSize = Integer.valueOf(String.valueOf(paramMap.get("judgePSize")));
			int blanksPageNow = Integer.valueOf(String.valueOf(paramMap.get("blanksPageNow")));
			int blanksPageSize = Integer.valueOf(String.valueOf(paramMap.get("blanksPageSize")));
			int answerPageNow = Integer.valueOf(String.valueOf(paramMap.get("answerPageNow")));
			int answerPageSize = Integer.valueOf(String.valueOf(paramMap.get("answerPageSize")));
			paramMap.put("optionPageSize", optionPageSize);
			paramMap.put("judgePSize", judgePSize);
			paramMap.put("blanksPageSize", blanksPageSize);
			paramMap.put("answerPageSize", answerPageSize);
			
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			System.out.println("最后的map"+paramMap);
			//通过课程号获取课程信息
			Map<String,Object> courseMap = courseDao.getCourseDetailById(paramMap);
			returnMap.put("courseMap", courseMap);
			//选择集合
			List<Map<String, Object>> optionList = new ArrayList<Map<String, Object>>();
			optionList =questionDao.getOptionQuestionListExcel(paramMap);
			if(optionList.size()!=0){
			titleMap.put("optionTitle", "选择题");
			returnMap.put("optionList", optionList);
			//判断集合
			List<Map<String, Object>> judgeList = new ArrayList<Map<String, Object>>();
			judgeList =questionDao.getJudgeQuestionListExcel(paramMap);
			if(judgeList.size()!=0){
				titleMap.put("judgeTitle", "判断题");
			}
			returnMap.put("judgeList", judgeList);
			//填空集合
			List<Map<String, Object>> blanksList = new ArrayList<Map<String, Object>>();
			blanksList =questionDao.getBlanksQuestionListExcel(paramMap);
			if(blanksList.size()!=0){
				titleMap.put("blanksTitle", "填空题");
			}
			returnMap.put("blanksList", blanksList);
			//简答集合
			List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
			answerList =questionDao.getAnswerQuestionListExcel(paramMap);
			if(answerList.size()!=0){
				titleMap.put("answerTitle", "简答题");
			}
			returnMap.put("answerList", answerList);
			returnMap.put("titleMap", titleMap);
			System.out.println("最后咋没查到呢"+returnMap);
			}
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  查询所选试题类型题库中是否存在
	 * @throws IOException
	 */
	public Map<String, Object> getQuestionsByExcel(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {
			
			String errMsg = "";
			//获取分页数据
			int optionPageNow = Integer.valueOf(String.valueOf(paramMap.get("optionPageNow")));
			int optionPageSize = Integer.valueOf(String.valueOf(paramMap.get("optionPageSize")));
//			int optionStartNum = pageUtil.getSqlStartPos(optionPageNow, optionPageSize);
			int judgePageNow = Integer.valueOf(String.valueOf(paramMap.get("judgePageNow")));
			int judgePSize = Integer.valueOf(String.valueOf(paramMap.get("judgePSize")));
//			int judgeStartNum = pageUtil.getSqlStartPos(judgePageNow, judgePSize);
			int blanksPageNow = Integer.valueOf(String.valueOf(paramMap.get("blanksPageNow")));
			int blanksPageSize = Integer.valueOf(String.valueOf(paramMap.get("blanksPageSize")));
//			int blanksStartNum = pageUtil.getSqlStartPos(blanksPageNow, blanksPageSize);
			int answerPageNow = Integer.valueOf(String.valueOf(paramMap.get("answerPageNow")));
			int answerPageSize = Integer.valueOf(String.valueOf(paramMap.get("answerPageSize")));
//			int answerStartNum = pageUtil.getSqlStartPos(answerPageNow, answerPageSize);
			paramMap.put("optionPageSize", optionPageSize);
			paramMap.put("judgePSize", judgePSize);
			paramMap.put("blanksPageSize", blanksPageSize);
			paramMap.put("answerPageSize", answerPageSize);
			
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId = "8888888";
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//通过教师号获取此教师所属课程
//			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
//			returnMap.put("courseList", courseList);
//			paramMap.put("courseList", courseList);
			System.out.println("最后的map"+paramMap);
			List<Map<String, Object>> optionList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> judgeList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> blanksList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
			//选择集合
//			if(optionPageNow!=0){
				optionList =questionDao.getOptionQuestionListExcel(paramMap);
				if(optionList.size()!=0){
					titleMap.put("optionTitle", "选择题");
				}
				returnMap.put("optionList", optionList);
//			}if(judgePageNow!=0){
				//判断集合
				judgeList =questionDao.getJudgeQuestionListExcel(paramMap);
				if(judgeList.size()!=0){
					titleMap.put("judgeTitle", "判断题");
				}
				returnMap.put("judgeList", judgeList);
//			}if(blanksPageNow!=0){
				//填空集合
				blanksList =questionDao.getBlanksQuestionListExcel(paramMap);
				if(blanksList.size()!=0){
					titleMap.put("blanksTitle", "填空题");
				}
				returnMap.put("blanksList", blanksList);
//			}if(answerPageNow!=0){
				//简答集合
				answerList =questionDao.getAnswerQuestionListExcel(paramMap);
				if(answerList.size()!=0){
					titleMap.put("answerTitle", "简答题");
				}
				returnMap.put("answerList", answerList);
//			}
			System.out.println("optionList"+optionList+"judgeList"+judgeList+"blanksList"+blanksList+"answerList"+answerList+"optionList长度"+optionList.size());
			boolean opFlag=false;
			boolean juFlag=false;
			boolean blFlag=false;
			boolean anFlag=false;
			if(optionList==null||optionList.size()==0||judgeList==null||judgeList.size()==0||blanksList==null||blanksList.size()==0||answerList==null||answerList.size()==0){
				if((optionList==null||optionList.size()==0)&&optionPageSize!=0){
					System.out.println("为啥没走这");
					opFlag = true;
					errMsg = "、选择题";
				}if((judgeList==null||judgeList.size()==0)&&judgePSize!=0){
					juFlag = true;
					errMsg=errMsg+"、判断题";
				}if((blanksList==null||blanksList.size()==0)&&blanksPageSize!=0){
					blFlag = true;
					errMsg=errMsg+"、填空题";
				}if((answerList==null||answerList.size()==0)&&answerPageSize!=0){
					anFlag = true;
					errMsg=errMsg+"、简答题";
				}
				String str = "";
				if(!(errMsg.equals(null))&&!(errMsg.equals(""))){
					System.out.println("这呢");
					str = PubMethods.getCharStr(errMsg);
//					str = "当前题库没有"+str+"是否要继续生成试题？";
					str = "当前题库没有"+str;
				}
				System.out.println("str"+str+"opFlag"+opFlag+"errMsg"+errMsg+"juFlag"+juFlag);
				if(opFlag&&juFlag&&blFlag&&anFlag){
					System.out.println("应该走着啊");
					returnMap.put("finalflag", "fail");
					returnMap.put("flag", "fail");
				}else{
					System.out.println("不可以走着啊");
					returnMap.put("finalflag", "success");
					returnMap.put("flag", "fail");
				}
				
				returnMap.put("errMsg", str);
			}else{
				System.out.println("难道走这了");
				returnMap.put("flag", "success");
				returnMap.put("finalflag", "success");
			}
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * 添加/编辑问题表单提交。
	 * @throws IOException
	 */
	public boolean addQuestion(Map<String,Object> paramMap) throws Exception {
		
		boolean flag = false;
		int questionType=0;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
//			//将题目类型转换
//			if(paramMap.get("type").equals("选择")){
//				questionType=1;
//			}if(paramMap.get("type").equals("判断")){
//				questionType=2;
//			}if(paramMap.get("type").equals("填空")){
//				questionType=3;
//			}if(paramMap.get("type").equals("简答")){
//				questionType=4;
//			}
//			paramMap.put("questionType", questionType);
			String optionMsg = (String) paramMap.get("optionMsg");;
			String ansquesContent = (String) paramMap.get("ansquesContent");
			if(!(String.valueOf(paramMap.get("optionMsg")).equals(null))&&!(String.valueOf(paramMap.get("optionMsg")).equals(""))){
//				System.out.println("没转换之前"+paramMap.get("optionMsg"));
				optionMsg = optionMsg.replaceAll("\n", "<br>");
				optionMsg = optionMsg.replaceAll("\r", "<br>");
//				System.out.println("转换之后"+optionMsg);
				paramMap.put("optionMsg", optionMsg);
			}
			if(!(String.valueOf(paramMap.get("ansquesContent")).equals(null))&&!(String.valueOf(paramMap.get("ansquesContent")).equals(""))){
				ansquesContent = ansquesContent.replaceAll("\n", "<br>");
				ansquesContent = ansquesContent.replaceAll("\r", "<br>");
				paramMap.put("ansquesContent", ansquesContent);
			}
			list.add(paramMap);
			System.out.println("最后的参数不对吗"+list);
			if((Integer)paramMap.get("operationType")==1){
				System.out.println("走1");
				//添加
				flag = questionDao.addQuestion(list);
			}else{
				System.out.println("走2");
				//编辑
				flag = questionDao.saveQuestion(paramMap);
			}
			
		} catch (Exception e) {
			throw e;
		}
		return flag;
	}
	
	/**
	 * @description  删除题库,传回题库id集合。List<String>形式   jsonStr = ["1","2","3"...]。 
	 * @param .List<Integer> paramList 题库id集合
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public boolean delQuestions(List<String> paramList) throws Exception {

		boolean resultFlag = false;
		try {
			//删除题库
			resultFlag = questionDao.delQuestions(paramList);
			 
		} catch (Exception e) {
			throw e;
		}
		return resultFlag;
	}
	
	/*
	 * 导入
	 */
	 public Map<String,Object> imQuestion(String file) throws Exception{
		//得到表格中所有的数据
		 Map<String,Object> resultMap = new HashMap<String,Object>();
		 resultMap = this.getAllByExcel(file);
       List<Map<String, Object>> listExcel= (List<Map<String, Object>>) resultMap.get("list");
       System.out.println("imQuestion得到表格中所有的数据"+listExcel);
       Map<String,Object> returnMap = new HashMap<String,Object>();
       if(listExcel!=null&&listExcel.size()!=0){
    	   for(int i=0;i<listExcel.size();i++){
    		   String optionMsg = (String) listExcel.get(i).get("optionMsg");
   			   String ansquesContent = (String) listExcel.get(i).get("ansquesContent");
   			if(!(String.valueOf(listExcel.get(i).get("optionMsg")).equals(null))&&!(String.valueOf(listExcel.get(i).get("optionMsg")).equals(""))){
//   				System.out.println("没转换之前"+listExcel.get(i).get("optionMsg"));
   				optionMsg = optionMsg.replaceAll("\n", "<br>");
   				optionMsg = optionMsg.replaceAll("\r", "<br>");
//   				System.out.println("转换之后"+optionMsg);
   				listExcel.get(i).put("optionMsg", optionMsg);
   			}
   			if(!(String.valueOf(listExcel.get(i).get("ansquesContent")).equals(null))&&!(String.valueOf(listExcel.get(i).get("ansquesContent")).equals(""))){
   				ansquesContent = ansquesContent.replaceAll("\n", "<br>");
   				ansquesContent = ansquesContent.replaceAll("\r", "<br>");
   				listExcel.get(i).put("ansquesContent", ansquesContent);
   			}
    	   }
    	  
    	   boolean flag1 = questionDao.addQuestion(listExcel);
    	   if(flag1){
    		   returnMap.put("flag", "success");
    		   System.out.println("导入成功");
    	   }else{
    		   System.out.println("导入失败");
    		   returnMap.put("flag", "fail");
    		   returnMap.put("errMsg", "填写数据不正确，导入失败");
    	   }
       }else{
    	   returnMap.put("flag", "fail");
    	   returnMap.put("errMsg", resultMap.get("errMsg"));
       }
       return returnMap;
   }
	 
	 /**
	    * 查询指定目录中电子表格中所有的数据
	    * @param file 文件完整路径
	    * @return
	    */
   public  Map<String, Object> getAllByExcel(String file){
       List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
       Map<String, Object> returnMap = new HashMap<String,Object>();
       try {
           Workbook rwb=Workbook.getWorkbook(new File(file));
           Sheet rs=rwb.getSheet(0);
           int clos=rs.getColumns();//得到所有的列
           int rows=rs.getRows();//得到所有的行
           int questionType = 0;
           System.out.println(clos+" rows:"+rows);
           int newRow = PubMethods.getNewRows(rows, rs);
           ok:
           for (int i = 2; i < newRow; i++) {
               for (int j = 1; j < clos; j++) {
            	   
            	   Map<String, Object> resultMap = new HashMap<String,Object>();
                   //第一个是列数，第二个是行数
            	   String questionName=rs.getCell(j++, i).getContents().trim();
                   String type=rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
                   System.out.println("type"+type);
                   if(type.equals("选择")||type.equals("判断")||type.equals("填空")||type.equals("简答")){
                	   System.out.println(1);
                	   if(type.equals("选择")){
          					questionType=1;
   	       			}if(type.equals("判断")){
   	       				questionType=2;
   	       			}if(type.equals("填空")){
   	       				questionType=3;
   	       			}if(type.equals("简答")){
   	       				questionType=4;
   	       			}
                      String optionMsg=rs.getCell(j++, i).getContents().trim();
                      if(optionMsg==null||optionMsg.equals("")){
                   	   optionMsg = "";
                      }
                      String ansquesContent = rs.getCell(j++, i).getContents().trim();
                      //通过课程名查询课程id
                      Map<String, Object> paramMap = new HashMap<String,Object>();
                      String courseName=rs.getCell(j++, i).getContents().trim();
                      System.out.println("courseName"+courseName);
                      paramMap.put("courseName", courseName);
                      Map<String, Object> courseMap = courseDao.getCourseDetailByName(paramMap);
//                      System.out.println("怎么空指针了"+courseMap);
                      int courseId=0;
                      if(courseMap!=null){
                    	   System.out.println(3);
	                   	   courseId = Integer.valueOf(String.valueOf(courseMap.get("courseId")));
	                   	   resultMap.put("questionName", questionName);
                          resultMap.put("questionType", questionType);
                          resultMap.put("optionMsg", optionMsg);
                          resultMap.put("ansquesContent", ansquesContent);
                          resultMap.put("courseId", courseId);
                          list.add(resultMap);
                          returnMap.put("list", list);
                      }else{
                    	  System.out.println(4);
                    	  list = null;
                    	  returnMap.put("list", list);
                    	  returnMap.put("errMsg", "所填课程不存在");
                    	  break ok;
                      }
                   }else{
                	   System.out.println(2);
                	   //说明填写数据不正确
                	   list = null;
                	   returnMap.put("list", list);
                 	   returnMap.put("errMsg", "所填问题类型不正确");
                	   break ok;
                   }
                   
               }
           }
       } catch (Exception e) {
           
           e.printStackTrace();
       } 
       return returnMap;
   }
   
   /**
	 * 在线预览表单提交
	 * @throws IOException
	 */
	public boolean addOnlineQuestion(Map<String,Object> paramMap,HttpSession session) throws Exception {
		
		boolean flag = false;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			
			//获取当前登陆人的工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId = "1210711012";
			paramMap.put("stuorteaId", stuorteaId);
			System.out.println("最后的参数不对吗"+paramMap);
			paramMap.put("teaId", stuorteaId);
			//查询当前老师当前课程是否有试卷
			Map<String,Object> quMap = questionDao.getOnlineQuestion(paramMap);
			System.out.println("quMap"+quMap);
			if(quMap==null||quMap.size()==0){
				//添加
				flag = questionDao.addOnlineQuestion(paramMap);
			}else{
				//修改
				flag = questionDao.updateOnlineQuestion(paramMap);
			}
			
			
		} catch (Exception e) {
			throw e;
		}
		return flag;
	}

	/**
	 * @param courseid,stuorteaid
	 * @return  通过课程id和当前登陆人所属老师的工号查询当前课程的试题
	 * @throws IOException
	 */
	public Map<String, Object> getOnlineQuestion(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {
			
			
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId = "2017060001";
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseDao.getStuCourse(paramMap);
			//通过学号查询所属教师
			List<Map<String,Object>> teaList = relationDao.getMyTeacherByCourseId (paramMap);
			//通过学号和课程号获取此学生所属老师，查出当前科目当前老师生成的试题
			if(teaList!=null&&teaList.size()!=0){
				paramMap.put("teaId", teaList.get(0).get("stuorteaId"));
				Map<String,Object> questonMap = questionDao.getOnlineQuestion(paramMap);
				if(questonMap!=null&&questonMap.size()!=0){
					returnMap.put("questonMap", questonMap);
					returnMap.put("courseList", courseList);
					returnMap.put("flag", "success");
					returnMap.put("errMsg", "生成试题成功");
				}else{
					//说明此教师没有课程
					returnMap.put("flag", "fail");
					returnMap.put("errMsg", "当前课程没有试题");
				}
			}else{
				//说明此学生没有所属教师
				returnMap.put("flag", "fail");
				returnMap.put("errMsg", "当前学生没有所属教师");
			}
			
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * 学生在线考试表单提交
	 * @throws IOException
	 */
	public Map<String,Object> addStuAnswerQuestion(Map<String,Object> paramMap,HttpSession session) throws Exception {
		
		boolean flag = false;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> returnMap = new HashMap<String,Object>();
		String textjson = "";
		String errStr = "";
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//选择题错误个数
		int opworcount = 0;
		//判断题错误个数 
		int judworcount = 0;
		//选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		try {
			
			//获取当前登陆人的学号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId="2017060001";
			paramMap.put("stuorteaId", stuorteaId);
			list = (List<Map<String, Object>>) paramMap.get("mapList");
			//通过问题主键查询question表查每道题的正确答案
			List<Map<String,Object>> questonList =  questionDao.getAllQuestionListById(list);
			//计算选择、判断错误个数和得分情况
			Map<String,Object> coutMap = this.coutMethod(questonList,list,paramMap);
			System.out.println("接到的集合是啥"+list);
			//将前台给的学生答案集合每个做空格、回车处理
			for(int j=0;j<list.size();j++){
				if(String.valueOf(list.get(j).get("ansquesContent"))!=null){
					String ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\n", "<br>");
					ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\r", "<br>");
					list.get(j).put("ansquesContent", ansquesContent);
				}
			}
			opworcount = Integer.valueOf(String.valueOf(coutMap.get("opworcount")));
			judworcount = Integer.valueOf(String.valueOf(coutMap.get("judworcount")));
			optionallsource = (BigDecimal) coutMap.get("optionallsource");
			judgeallsource = (BigDecimal) coutMap.get("judgeallsource");
			errList = (List<Integer>) coutMap.get("errList");
			System.out.println("最后的集合怎么回事"+list);
			System.out.println("选择题错误个数"+opworcount+"判断题错误个数"+judworcount+"看看集合对吗"+errList);
			paramMap.put("opworcount", opworcount);
			paramMap.put("judworcount", judworcount);
			paramMap.put("optionallsource", optionallsource);
			paramMap.put("judgeallsource", judgeallsource);
			textjson = mapper.writeValueAsString(list);
			System.out.println("大的集合转换为对象后"+textjson);
			paramMap.put("textjson", textjson);
			errStr = mapper.writeValueAsString(errList);
			System.out.println("大的集合转换为字符串后"+errStr);
			paramMap.put("errList", errStr);
			System.out.println("最后的map"+paramMap);
			//查询当前学生是否已经答过题
			Map<String,Object> stuquMap = questionDao.getStuAnswerByOnIdAndCouId(paramMap);
			if(stuquMap!=null){
				//修改
				flag = questionDao.updateStuAnswerQuestion(paramMap);
			}else{
				//添加
				flag = questionDao.addStuAnswerQuestion(paramMap);
			}
			
			returnMap.put("flag", flag);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * @param 
	 * @return  在线批阅列表
	 * @throws IOException
	 */
	public Map<String, Object> getAllStuExamList(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
//			String stuorteaId = "1210711012";
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			System.out.println("最后给数据库传的是什么参数啊"+paramMap);
			//该教师的当前所属的所有班级学生考试情况
			List<Map<String,Object>> memList = questionDao.getAllStuExamList(paramMap);
			returnMap.put("memList", memList);
			System.out.println("最后的map"+paramMap);
			//通过教师号获取此教师所属班级(不要结课的班级)
			List<String> classList = relStuClassDao.getClassByStuorteaIdAndNo(paramMap);
			returnMap.put("classList", classList);
			//通过教师号获取此教师所属课程
			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
			returnMap.put("courseList", courseList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = questionDao.getAllStuExamList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * @param 通过课程id和学号查询当前课程的试题
	 * @return 通过课程id和学号查询当前课程的试题
	 * @throws IOException
	 */
	public Map<String, Object> getMarkStuQuestion(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
		List<Integer> errList = new ArrayList<Integer>();
		Map<String,Object> newQuestion = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		try {
			System.out.println("最后的map"+paramMap);
			//通过课程id和学号查询当前课程的试题
			Map<String,Object> question = questionDao.getMarkStuQuestion(paramMap);
			//取出学生答案解析成对象后传给前台
			String textjson = (String) question.get("textjson");
			answerList = mapper.readValue(textjson, answerList.getClass());
			//将错误题集合转换成对象传给前台
			String errstr =  (String) question.get("errlist");
			errList = mapper.readValue(errstr, errList.getClass());
			System.out.println("取到的"+errstr);
			newQuestion.put("answerList", answerList);
			newQuestion.put("errList", errList);
			newQuestion.put("optionallsource", question.get("optionallsource"));
			newQuestion.put("judgeallsource", question.get("judgeallsource"));
			newQuestion.put("blankscount", question.get("blankscount"));
			newQuestion.put("answersource", question.get("answersource"));
			newQuestion.put("stuorteaId", question.get("stuorteaId"));
			newQuestion.put("judworcount", question.get("judworcount"));
			newQuestion.put("state", question.get("state"));
			newQuestion.put("answercount", question.get("answercount"));
			newQuestion.put("courseId", question.get("courseId"));
			newQuestion.put("blanksallsource", question.get("blanksallsource"));
			newQuestion.put("oTestJson", question.get("oTestJson"));
			newQuestion.put("opworcount", question.get("opworcount"));
			newQuestion.put("stuquId", question.get("stuquId"));
			newQuestion.put("courseName", question.get("courseName"));
			newQuestion.put("classId", question.get("classId"));
			newQuestion.put("onlinequestionId", question.get("onlinequestionId"));
			returnMap.put("question", newQuestion);
			
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 *编辑在线考试、编辑成绩表
	 * @throws IOException
	 */
	public Map<String,Object> addExameSource(Map<String,Object> paramMap,HttpSession session) throws Exception {
		System.out.println("编辑在线考试、编辑成绩表"+paramMap);
		boolean flag = false;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> sourceMap = new HashMap<String,Object>();
		try {
			paramMap.put("examSource", paramMap.get("examesource"));
			System.out.println("examSource"+paramMap.get("examesource"));
			//查询成绩表中的平时成绩
			Map<String,Object> examMap = sourceDao.getExamBySidAndCourseId(paramMap);
			System.out.println("该学生有成绩吗"+examMap);
			if(examMap!=null){
				//计算该学生的总分数插入到exame表
				sourceMap.put("classId", paramMap.get("classId"));
				sourceMap.put("courseId", paramMap.get("courseId"));
				//平时成绩换算值
				BigDecimal finPromaceSource = sourceActionImpl.proSource(sourceMap, examMap,session);
				//考试成绩换算值
				BigDecimal examSource = sourceActionImpl.examSource(sourceMap, paramMap,session);
				System.out.println("考试成绩"+examSource+"平时成绩"+finPromaceSource);
				//学生最后的成绩
			   BigDecimal finSumSource = finPromaceSource.add(examSource);
			   paramMap.put("sumSource", finSumSource);
			   System.out.println("学生的最后成绩"+finSumSource+"传入参数是"+paramMap);
				//编辑成绩表，将学生总成绩插入数据库。
				flag = questionDao.saveQuestionByStuId(paramMap);
				//编辑学生在线考试表，将填空、简答的错误数量和分数插入数据库。
				flag = questionDao.addExameSource(paramMap);
				String resultMark = (flag == true) ? "success" : "fail";
				resultMap.put("resultMark", resultMark);
			}else{
				//说明该学生没有交作业或者作业没有被评价，则只将考试成绩插入成绩表中
				String sId = String.valueOf(paramMap.get("stuorteaId"));
				//考试成绩换算值
				BigDecimal examSource = sourceActionImpl.examSource(paramMap, paramMap,session);
				System.out.println("考试成绩"+examSource);
				paramMap.put("sumSource", examSource);
				paramMap.put("stuorteaId", sId);
				System.out.println("最后的参数"+paramMap);
				Map<String,Object> map = sourceDao.getExamBySidAndCourseId(paramMap);
				System.out.println("该学生有成绩？"+map);
				if(map!=null){
					//编辑成绩表，将学生总成绩插入数据库。
					flag = sourceDao.updateSorceBySIdAndMark(paramMap);
				}else{
					//t添加成绩表，将学生总成绩插入数据库。
					flag = sourceDao.addExamByMark(paramMap);
				}
				
				//编辑学生在线考试表，将填空、简答的错误数量和分数插入数据库。
				flag = questionDao.addExameSource(paramMap);
				String resultMark = (flag == true) ? "success" : "fail";
				resultMap.put("resultMark", resultMark);
				
			}
			
		} catch (Exception e) {
			throw e;
		}
		return resultMap;
	}
	
	//计算选择、判断错误个数和得分情况
	public Map<String,Object> coutMethod(List<Map<String,Object>> questonList,List<Map<String,Object>> list,Map<String,Object> paramMap){
		//选择题错误个数
		int opworcount = 0;
		//判断题错误个数 
		int judworcount = 0;
		//选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		//循环集合计算选择判断错误个数和得分
		for(int i=0;i<questonList.size();i++){
			for(int j=0;j<list.size();j++){
				if((Integer)questonList.get(i).get("questionType")==1||(Integer)questonList.get(i).get("questionType")==2){
					if(Integer.valueOf(String.valueOf(list.get(j).get("questionId")))==Integer.valueOf(String.valueOf(questonList.get(i).get("questionId")))){
						//判断学生答案是否正确
						if(String.valueOf(String.valueOf(list.get(j).get("ansquesContent")).toUpperCase()).equals(String.valueOf(String.valueOf(questonList.get(i).get("ansquesContent")).toUpperCase().charAt(0)))&&(Integer)(questonList.get(i).get("questionType"))==1){
							BigDecimal optionSource = new BigDecimal(String.valueOf(paramMap.get("optionSource")));
							optionallsource = optionallsource.add(optionSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).toUpperCase().equals(String.valueOf(String.valueOf(questonList.get(i).get("ansquesContent")).toUpperCase().charAt(0))))&&(Integer)(questonList.get(i).get("questionType"))==1){
							opworcount = opworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
						if(String.valueOf(list.get(j).get("ansquesContent")).equals(String.valueOf(questonList.get(i).get("ansquesContent")))&&(Integer)(questonList.get(i).get("questionType"))==2){
							BigDecimal judgeSource = new BigDecimal(String.valueOf(paramMap.get("judgeSource")));
							judgeallsource = judgeallsource.add(judgeSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).equals(String.valueOf(questonList.get(i).get("ansquesContent"))))&&(Integer)(questonList.get(i).get("questionType"))==2){
							judworcount = judworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
					}
				}
			}
		}
		paramMap.put("errList", errList);
		paramMap.put("optionallsource", optionallsource);
		paramMap.put("opworcount", opworcount);
		paramMap.put("judgeallsource", judgeallsource);
		paramMap.put("judworcount", judworcount);
		return paramMap;
	}
}
